<template>
  <div class="whole">
    <div class="login">
      <div class="header">
        <h2>小型规模化猪场管理系统</h2>
      </div>
      <div class="content">
        <div class="input" style="width: 450px">
          <el-input
            v-model="state.username"
            placeholder="请输入账号"
          ></el-input>
        </div>
        <div class="input" style="width: 450px">
          <el-input
            v-model="state.password"
            placeholder="请输入密码"
            show-password
          ></el-input>
        </div>
        <div class="btn">
          <el-button type="primary" @click="login">登录</el-button>
          <el-button type="primary" @click="toRegister">去注册</el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script  setup>
// export default {
//   name: "Login"
// }
import { createAPI } from "@/utils/request";
import { reactive } from "vue";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useStore } from "vuex";
const router = useRouter();
const store = useStore();
const login = () => {
  // router.push({ name: 'admin' })
  console.log(state.username);
  console.log(state.password);
  if (state.username === "" || state.password === "") {
    ElMessage({
      message: "您输入的用户名和密码为空，请重新输入",
      type: "error",
      duration: 5 * 1000,
    });
    return null;
  } else {
    const formData = new FormData();
    formData.append("username", state.username);
    formData.append("password", state.password);
    createAPI("/login", "post", formData).then((res) => {
      if (res.data.status === 200) {
        console.log(res.data.obj.token);
        store.commit("setToken", res.data.obj.token)
        ElMessage({
          type: 'success',
          message: '登录成功',
        })
        setTimeout(() =>{
          console.log(store.state.token);
          router.push("/admin");
        },6000
      )
      }
    });
  }
};
const toRegister = () => {
  router.push("/register");
};

const state = reactive({
  username: "",
  password: "",
});
</script>

<style scoped>
* {
  margin: 0;
}
.whole {
  width: 100%;
  height: 100vh;
  background-image: url(./imgs/login-bg.jpg);
  background-size: 100%;
}
.login {
  position: absolute;
  left: 39%;
  top: 30%;
  width: 25%;
  height: 300px;
  background: rgba(255, 255, 255, 0.3);
  overflow: hidden;
}
.header h2 {
  width: 100%;
  line-height: 50px;
  text-align: center;
  font-size: 20px;
  color: #bbb;
  border-bottom: 1px solid #ddd;
}
.content {
  width: 100%;
}
.content .input {
  margin: 20px;
}

.btn {
  width: 100%;
  margin-top: 40px;
  text-align: center;
}
.el-button + .el-button {
  margin-left: 50px;
}
</style>
